package com.example.campus_order_sb.service;

import com.example.campus_order_sb.dto.FoodRequest;
import com.example.campus_order_sb.entity.Food;
import com.example.campus_order_sb.repository.FoodRepository;
import com.example.campus_order_sb.repository.OrderItemRepository;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class FoodServiceImpl implements FoodService {

    @Autowired
    private FoodRepository foodRepository;

    @Autowired
    private OrderItemRepository orderItemRepository;

    @Override
    public List<Food> getAllFoods() {
        return foodRepository.findAll();
    }

    @Override
    public Food getFoodById(Integer id) {
        return foodRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("菜品不存在: " + id));
    }

    @Override
    @Transactional
    public Food createFood(FoodRequest foodRequest) {
        Food food = new Food();
        food.setCategoryId(foodRequest.getCategoryId());
        food.setName(foodRequest.getName());
        food.setPrice(foodRequest.getPrice());
        food.setImage(foodRequest.getImage());
        food.setDescription(foodRequest.getDescription());

        return foodRepository.save(food);
    }

    @Override
    @Transactional
    public Food updateFood(Integer id, FoodRequest foodRequest) {
        Food food = foodRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("菜品不存在: " + id));

        food.setCategoryId(foodRequest.getCategoryId());
        food.setName(foodRequest.getName());
        food.setPrice(foodRequest.getPrice());
        food.setImage(foodRequest.getImage());
        food.setDescription(foodRequest.getDescription());

        return foodRepository.save(food);
    }

    @Override
    @Transactional
    public void deleteFood(Integer id) {
        Food food = foodRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("菜品不存在: " + id));

        // 检查是否有订单项引用此菜品
        boolean hasOrderItems = orderItemRepository.existsByFoodId(id);
        if (hasOrderItems) {
            throw new IllegalStateException("无法删除菜品，该菜品已被订单引用");
        }

        foodRepository.delete(food);
    }
}
